<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/5/28
 * Time: 下午6:33
 */

namespace EasySwoole\EasySwoole;


use App\Process\CountInc;
use App\Process\FormId;
use App\Process\MessageCreate;
use App\Process\MessageCustorm;
use App\Process\MessagePush;
use App\Process\StatisticsCounts;
use App\Process\UserLogin;
use App\Utility\Pool\RedisDatasPool;
use App\Utility\Pool\RedisPool;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use App\Process\HotReload;
use EasySwoole\Http\Request;
use EasySwoole\Http\Message\Status;
use EasySwoole\Http\Response;
use EasySwoole\Utility\File;
use EasySwoole\Component\Pool\PoolManager;
use App\Utility\Pool\MysqlPool;

class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        define( 'APP_PATH', __DIR__.'/App/' );
        date_default_timezone_set('PRC');
        //引用自定义文件配置
        self::loadConf();
        //注册mysql数据库连接池
        PoolManager::getInstance()->register(MysqlPool::class, Config::getInstance()
            ->getConf('database.pool_max_num'))
            ->setMinObjectNum((int)Config::getInstance()->getConf('database.pool_min_num'));
        // 注册redis连接池
        PoolManager::getInstance()->register(RedisPool::class, Config::getInstance()
            ->getConf('redis.pool_max_num'))
            ->setMinObjectNum((int)Config::getInstance()->getConf('redis.pool_min_num'));
        PoolManager::getInstance()->register(RedisDatasPool::class, Config::getInstance()
            ->getConf('redis2.pool_max_num'))
            ->setMinObjectNum((int)Config::getInstance()->getConf('redis2.pool_min_num'));
    }

    public static function mainServerCreate(EventRegister $register)
    {
        // 自定义进程注册
        $swooleServer = ServerManager::getInstance()->getSwooleServer();
        $swooleServer->addProcess((new HotReload('HotReload', ['disableInotify' => false]))->getProcess());
        //消息创建
        $swooleServer->addProcess((new MessageCreate('message-create'))->getProcess());
//        //消息推送
        for ($i = 0 ;$i < 30;$i++){
            $swooleServer->addProcess((new MessagePush("message-push_{$i}"))->getProcess());
        }
        //统计自增
        $swooleServer->addProcess((new CountInc('count-inc'))->getProcess());
        //formid收集
        for ($i = 0 ;$i < 5;$i++){
            $swooleServer->addProcess((new FormId("formid_{$i}"))->getProcess());
        }
        //客服消息
//        for ($i = 0 ;$i < 5;$i++){
//            $swooleServer->addProcess((new MessageCustorm("message-custorm_{$i}"))->getProcess());
//        }
        //用户登录
        $swooleServer->addProcess((new UserLogin('user_login'))->getProcess());
        // 统计小程序浏览信息
        $swooleServer->addProcess((new StatisticsCounts('statistics_counts'))->getProcess());
        //注册onWorkerStart回调事件
        $register->add($register::onWorkerStart, function (\swoole_server $server, int $workerId) {
            if ($server->taskworker == false) {
                //新增preload方法,可在程序启动后预创建连接,避免在启动时突然大量请求,造成连接来不及创建从而失败的问题.
                //预创建数量,必须小于连接池最大数量
                PoolManager::getInstance()->getPool(MysqlPool::class)->preLoad(5);
                PoolManager::getInstance()->getPool(RedisPool::class)->preLoad(5);
            }
        });
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        //跨域
        $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        $response->withHeader('Access-Control-Allow-Credentials', 'true');
        $response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        if ($request->getMethod() === 'OPTIONS') {
            $response->withStatus(Status::CODE_OK);
            $response->end();
        }
        $response->withHeader('Access-Control-Allow-Origin', '*');
    }

    public static function onReceive(\swoole_server $server, int $fd, int $reactor_id, string $data):void
    {

    }

    /**
     * 引用自定义配置文件
     * @throws \Exception
     */
    public static function loadConf()
    {
        $files = File::scanDirectory(EASYSWOOLE_ROOT . '/App/Config');
        if (is_array($files)) {
            foreach ($files['files'] as $file) {
                $fileNameArr = explode('.', $file);
                $fileSuffix = end($fileNameArr);
                if ($fileSuffix == 'php') {
                    Config::getInstance()->loadFile($file);
                }
            }
        }
    }

}
